package controllers

import (
	"fmt"
	"github.com/flaravel/quanlaolao/pkg/logger"
	"github.com/syyongx/php2go"
	"gorm.io/gorm"
	"net/http"
)

type BaseController struct {
}

// ResposeForSQLError 处理 SQL 错误并返回
func (bc BaseController) ResposeForSQLError(w http.ResponseWriter, err error) {
	if err == gorm.ErrRecordNotFound {
		// 3.1 数据未找到
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprint(w, "404 数据未找到")
	} else {
		// 3.2 数据库错误
		logger.LogError(err)
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprint(w, "500 服务器内部错误")
	}
}

func (bc BaseController) Success(w http.ResponseWriter,params interface{})  {
	w.Header().Set("Content-Type", "text/json; charset=utf-8")
	data := make(map[string]interface{})
	data["code"] = http.StatusOK
	data["message"] = "请求成功"
	data["data"] = params
	cpsJson, _ := php2go.JSONEncode(data)
	fmt.Fprintf(w,string(cpsJson))
}

func (bc BaseController) Error(w http.ResponseWriter,msg interface{})  {
	w.Header().Set("Content-Type", "text/json; charset=utf-8")
	data := make(map[string]interface{})
	data["code"] = http.StatusUnprocessableEntity
	data["message"] = msg
	w.WriteHeader(http.StatusUnprocessableEntity)
	cpsJson, _ := php2go.JSONEncode(data)
	fmt.Fprintf(w,string(cpsJson))
 }

func (bc BaseController) Message(w http.ResponseWriter,msg interface{})  {
	w.Header().Set("Content-Type", "text/json; charset=utf-8")
	data := make(map[string]interface{})
	data["code"] = http.StatusOK
	data["message"] = msg
	w.WriteHeader(http.StatusOK)
	cpsJson, _ := php2go.JSONEncode(data)
	fmt.Fprintf(w,string(cpsJson))
}
